package com.ruoyi.flowable.listener;

import com.alibaba.druid.util.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.flowable.service.IActRejectRecordService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.delegate.TaskListener;
import org.flowable.task.service.delegate.DelegateTask;
import org.springframework.stereotype.Component;

/**
 * 通用驳回监听器
 */
@Slf4j
@Component("rejectTaskListener")
public class RejectTaskListener implements TaskListener {

    @Override
    public void notify(DelegateTask delegateTask) {
        log.info("=== 通用驳回监听器开始执行 ===");
        try {
            // 手动获取 Spring Bean
            IActRejectRecordService actRejectRecordService = SpringUtils.getBean(IActRejectRecordService.class);
            String taskId = delegateTask.getId();
            String processInstanceId = delegateTask.getProcessInstanceId();
            String rejectReason = getRejectReason(delegateTask);
            // 在驳回记录表中添加记录
            actRejectRecordService.addRejectRecord(processInstanceId, taskId, rejectReason);
            log.info("驳回记录添加成功，流程实例ID: {}, 原因: {}", processInstanceId, rejectReason);
        } catch (Exception e) {
            log.error("添加驳回记录失败", e);
            // 不抛出异常，避免影响流程
        }
    }

    private String getRejectReason(DelegateTask delegateTask) {
        // 从流程变量中获取驳回原因
        String rejectReason = (String) delegateTask.getVariable("rejectReason");
        if (StringUtils.isEmpty(rejectReason)) {
            rejectReason = (String) delegateTask.getVariable("comment");
        }
        if (StringUtils.isEmpty(rejectReason)) {
            rejectReason = "系统自动驳回";
        }
        return rejectReason;
    }
}
